﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using WBasicClassLib.IniByXml;

namespace IniByXmlReader_Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.写入配置文件信息
            IniByXmlWriter Writer = new IniByXmlWriter("Test.xml", Encoding.GetEncoding("utf-8"));
            Writer.WriteInAElement(
                new XElement("书目1",
                    new XAttribute("书名", "CSS基础教程"),
                    new XText("人民邮电出版社"))
                    );
            Writer.WriteInAElement(
                new XElement("书目2",
                    new XAttribute("书名", "C++沉思录"),
                    new XText("人民邮电出版社"))
                    );
            Writer.WriteInAElement(
                new XElement("书目3",
                    new XAttribute("书名", "人兽鬼"),
                    new XText("三联书店"))
                    );
            Writer.WriteInAElement(
                new XElement("书目4",
                    new XAttribute("书名", "爱的教育"),
                    new XText("长春出版社"))
                    );
            Writer.Save();

            //2.读取配置文件信息
            IniByXmlReader Reader = new IniByXmlReader("Test.xml");
            Console.WriteLine("单个Element:");
            Console.WriteLine(Reader.GetElement("书目3"));
            Console.WriteLine("单个Attribute:");
            Console.WriteLine(Reader.GetAttribute(Reader.GetElement("书目3"), "书名"));
            Console.WriteLine("对单个Element的描述");
            Console.WriteLine(Reader.GetDescription(Reader.GetElement("书目3")));
            Console.WriteLine("显示所有出版社为人民邮电出版社的书目信息");
            IEnumerable<XElement> selector = Reader.GetAllElements().Where(c => c.Value == "人民邮电出版社").Select(c=>c);
            foreach(XElement s in selector)
            {
                Console.WriteLine(s);
            }

            //3.功能增强，使用委托或者Lambda表达式来选择元素
            Console.WriteLine("显示用Lambda表达式指定的书目信息(s=>s.Name==\"书目1\")");
            List<XElement> SelectElement = Reader.GetElements(s => s.Name == "书目1");
            foreach (XElement elem in SelectElement)
            {
                Console.WriteLine(elem);
            }

            //4.修改元素属性值
            Console.WriteLine("修改书目3的书名");
            Console.WriteLine("修改是否成功：" + Reader.UpdateAttribute("书目3", "书名", "我被修改了！").ToString());
            Reader.Save();
            Console.Write("书目3现在的书名：");
            Console.WriteLine(Reader.GetAttribute(Reader.GetElement("书目3"), "书名"));

            //5.试图修改不存在的元素的属性
            Console.WriteLine("试图修改不存在的元素的属性");
            Console.WriteLine("是否成功：" + Reader.UpdateAttribute("书目?", "书名", "试图修改不存在的元素的属性！").ToString());

            Console.ReadLine();
        }
    }
}
